package cn.com.pajx.pajx_visitor_v3.utils;

import static cn.com.pajx.pajx_visitor_v3.utils.FileUtil.getSize;

import android.animation.Animator;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.provider.Settings;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.View;
import android.view.ViewPropertyAnimator;
import android.view.WindowManager;
import android.webkit.WebSettings;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;

import java.util.Hashtable;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;

import cn.com.pajx.pajx_visitor_v3.BaseApp;


/**
 * create by ruancw on 2024/2/28.
 * 通用方法工具类
 */

public class CommonUtil {

    private static final long B = 1;
    private static final long KB = B * 1024;
    private static final long MB = KB * 1024;
    private static final long GB = MB * 1024;

    /**
     * 格式化文件大小<b> 带有单位
     *
     * @param size 文件大小
     * @return 带单位的字符
     */
    public static String formatFileSize(long size) {
        StringBuilder sb = new StringBuilder();
        String u;
        double tmpSize;
        if (size < KB) {
            sb.append(size / 1024).append("KB");
            return sb.toString();
        } else if (size < MB) {
            tmpSize = getSize(size, KB);
            u = "KB";
        } else if (size < GB) {
            tmpSize = getSize(size, MB);
            u = "MB";
        } else {
            tmpSize = getSize(size, GB);
            u = "GB";
        }
        return sb.append(twoDot(tmpSize)).append(u).toString();
    }

    /**
     * 获取状态栏高度
     *
     * @param activity activity
     * @return int
     */
    public static int getStatusBarHeight(Activity activity) {
        Resources resources = activity.getResources();
        int resourceId = resources.getIdentifier("status_bar_height", "dimen", "android");
        return resources.getDimensionPixelSize(resourceId);
    }

    /**
     * 获取屏幕的宽度（单位：px）
     *
     * @return 屏幕宽px
     */
    public static int getScreenWidth() {
        WindowManager windowManager = (WindowManager) BaseApp.getInstance().getSystemService(Context.WINDOW_SERVICE);
        DisplayMetrics dm = new DisplayMetrics();// 创建了一张白纸
        assert windowManager != null;
        windowManager.getDefaultDisplay().getMetrics(dm);// 给白纸设置宽高
        return dm.widthPixels;
    }

    /**
     * 获取屏幕的高度（单位：px）
     *
     * @return 屏幕高px
     */
    public static int getScreenHeight() {
        WindowManager windowManager = (WindowManager) BaseApp.getInstance().getSystemService(Context.WINDOW_SERVICE);
        DisplayMetrics dm = new DisplayMetrics();// 创建了一张白纸
        assert windowManager != null;
        windowManager.getDefaultDisplay().getMetrics(dm);// 给白纸设置宽高
        return dm.heightPixels;
    }

    /**
     * 获取当前app的版本名
     *
     * @return 版本号1.0.1
     */
    @SuppressLint("WrongConstant")
    public static String getVersionName(Context c) {
        String verName = null;
        try {
            verName = c.getPackageManager().getPackageInfo(c.getPackageName(),
                    1).versionName;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return verName;
    }

    /**
     * 获取当前app的版本号
     *
     * @return 版本号100
     */
    public static int getVersionCode(Context c) {
        int verCode = 0;
        try {
            verCode = c.getPackageManager().getPackageInfo(c.getPackageName(),
                    0).versionCode;
        } catch (Exception e) {
            e.printStackTrace();

        }
        return verCode;
    }

    /**
     * 获取手机型号
     *
     * @return 手机型号
     */
    public static String getSystemModel() {
        try {
            return Build.MODEL;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "model";
    }

    /**
     * 保留两位小数
     *
     * @param d double
     * @return String
     */
    @SuppressLint("DefaultLocale")
    private static String twoDot(double d) {
        return String.format("%.2f", d);
    }

    /**
     * 点击动画
     *
     * @param v view
     */
    public static void animateClickView(final View v,
                                        final ClickAnimation callback) {
        ViewPropertyAnimator animator = v.animate();//ViewPropertyAnimator 查看属性动画
        animator.setListener(new Animator.AnimatorListener() {

            @Override
            public void onAnimationStart(Animator animation) {

            }

            @Override
            public void onAnimationRepeat(Animator animation) {

            }

            @Override
            public void onAnimationEnd(Animator animation) {
                v.setScaleX(1);
                v.setScaleY(1);
                v.setAlpha(1);
                if (callback != null) {
                    callback.onClick(v);
                }
            }

            @Override
            public void onAnimationCancel(Animator animation) {

            }
        });
        animator.scaleX(2).scaleY(2).alpha(0.0f).start();

    }

    /**
     * 动画回调接口
     */
    public interface ClickAnimation {
        void onClick(View v);
    }

    // 判断是否为emial
    public static boolean checkEmail(String emailstr) {
        Pattern p = Pattern.compile("^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\\.)+[a-z]{2,3}$");
        Matcher m = p.matcher(emailstr);
        return m.matches();
    }

    /**
     * 判定EditText 输入是否为汉字
     *
     * @param c 字符
     * @return boolean
     */
    private static boolean isChinese(char c) {
        Character.UnicodeBlock ub = Character.UnicodeBlock.of(c);
        return ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS
                || ub == Character.UnicodeBlock.CJK_COMPATIBILITY_IDEOGRAPHS
                || ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS_EXTENSION_A
                || ub == Character.UnicodeBlock.GENERAL_PUNCTUATION
                || ub == Character.UnicodeBlock.CJK_SYMBOLS_AND_PUNCTUATION
                || ub == Character.UnicodeBlock.HALFWIDTH_AND_FULLWIDTH_FORMS
                && c >= 0x4E00 && c <= 0x9FA5;
    }

    /**
     * 检测String是否全是中文（这里输入名字的时候 有点问题：就是可以输入汉语“，！？”。 所以用下面的正则表达式再次进行判定）
     *
     * @param name 名字
     * @return boolean
     */
    public static boolean checkIsChinese(String name) {
        boolean res = true;
        char[] cTemp = name.toCharArray();
        for (int i = 0; i < name.length(); i++) {
            if (!isChinese(cTemp[i])) {
                res = false;
                break;
            }
        }
        return res;
    }

    /**
     * 用正则表达式 限定EditText只可以输入汉字
     *
     * @param str 字符串
     * @return 字符串
     * @throws PatternSyntaxException PatternSyntaxException
     */
    public static String stringFilter(String str) throws PatternSyntaxException {
        // 只允许字母、数字和汉字
        String regEx = "[^a-zA-Z0-9\u4E00-\u9FA5]";
        Pattern p = Pattern.compile(regEx);
        Matcher m = p.matcher(str);
        return m.replaceAll("").trim();
    }

    /**
     * 验证是否是手机号
     *
     * @param mobiles 号码
     * @return true  是手机号
     */
    public static boolean isMobilePhone(String mobiles) {
        /*
         * 移动：134、135、136、137、138、139、150、151、157(TD)、158、159、187、188
         * 联通：130、131、132、152、155、156、185、186 电信：133、153、180、189、（1349卫通）
         * 总结起来就是第一位必定为1，第二位必定为3或5或8，其他位置的可以为0-9
         */
        String telRegex = "[1][34587]\\d{9}";// "[1]"代表第1位为数字1，"[358]"代表第二位可以为3、5、8中的一个，"\\d{9}"代表后面是可以是0～9的数字，有9位。
        if (TextUtils.isEmpty(mobiles))
            return false;
        else
            return mobiles.matches(telRegex);
    }

    // 检验是否是6位数字的验证码格式
    public static boolean isVerifyCode(String code) {
        return code.matches("^\\d{6}$");
    }

    /**
     * 判断是否打开了允许虚拟位置,如果打开了 则弹窗让他去关闭
     */
    public static boolean isAllowMockLocation(final Activity context) {
        boolean isOpen = Settings.Secure.getInt(context.getContentResolver(), Settings.Secure.ALLOW_MOCK_LOCATION, 0) != 0;

        ///该判断API是androidM以下的API,由于Android M中已经没有了关闭允许模拟位置的入口,所以这里一旦检测到开启了模拟位置,并且是android M以上,则
        //默认设置为未有开启模拟位置

        if (isOpen && Build.VERSION.SDK_INT > 22) {
            isOpen = false;
        }
        return isOpen;
    }

    /**
     * 字符串转数组
     *
     * @param str 字符串
     * @return 字符串数组
     */
    public static String[] changeToArr(String str) {

        if ("".equals(str) || "null".equals(str) || str == null)
            return null;
        String[] ret = new String[]{};
        if (str.lastIndexOf(",") == str.length() - 1) {
            str = str.substring(0, str.length() - 1);
            ret = str.split(",");
        }
        return ret;
    }

    public static void callPhone(Context mContext, String phone) {
        Intent intent = new Intent(Intent.ACTION_DIAL);
        Uri data = Uri.parse("tel:" + phone);
        intent.setData(data);
        mContext.startActivity(intent);
    }

    /**
     * 获取32随机码
     *
     * @return 字符串
     */
    public static String getRandomUUID() {
        return UUID.randomUUID().toString().replace("-", "");
    }


    /* 获取小于等于2位的名字*/
    public static String getAvatarName(String name) {
        if (TextUtils.isEmpty(name) || TextUtils.isEmpty(name.trim())) {
            name = "无名";
        }
        String avarName;
        if (name.length() > 2) {
            avarName = name.substring(name.length() - 2);
        } else {
            avarName = name;
        }
        return avarName;
    }

    /**
     * 隐藏身份证中间8位
     *
     * @param id_card 41052319********10
     * @return 字符串
     */
    public static String hideIdCard(String id_card) {
        if (TextUtils.isEmpty(id_card)) return "";
        StringBuilder stringBuilder = new StringBuilder(id_card);
        stringBuilder.replace(8, 16, "********");
        return stringBuilder.toString();
    }

    /**
     * 隐藏身份证中间8位
     *
     * @param name 测试
     * @return 字符串
     */
    public static String hideName(String name) {
        if (TextUtils.isEmpty(name)) return "未知";
        StringBuilder stringBuilder = new StringBuilder(name);
        stringBuilder.replace(1, 2, "*");
        return stringBuilder.toString();
    }

    public static String hidePhoneNumber(String phone) {
        if (TextUtils.isEmpty(phone) || phone.length() != 11) {
            return phone;
        }
        String hidePhone = phone.replaceAll("(\\d{3})\\d{4}(\\d{4})", "$1****$2");
        return hidePhone;
    }

    public static Bitmap encodeAsBitmap(String content, BarcodeFormat type, int bmpWidth, int bmpHeight)
            throws WriterException {
        Hashtable<EncodeHintType, String> mHashtable = new Hashtable<>();
        mHashtable.put(EncodeHintType.CHARACTER_SET, "UTF-8");
        BitMatrix matrix = new MultiFormatWriter().encode(content, type, bmpWidth, bmpHeight, mHashtable);
        int width = matrix.getWidth();
        int height = matrix.getHeight();
        int[] pixels = new int[width * height];
        for (int y = 0; y < height; y++) {
            for (int x = 0; x < width; x++) {
                if (matrix.get(x, y)) {
                    pixels[y * width + x] = 0xff000000;
                } else {
                    pixels[y * width + x] = 0xffffffff;
                }
            }
        }
        Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
        bitmap.setPixels(pixels, 0, width, 0, 0, width, height);
        return bitmap;
    }

    public static String getUserAgent(Context context) {
        String userAgent;
        try {
            userAgent = WebSettings.getDefaultUserAgent(context);
        } catch (Exception e) {
            userAgent = System.getProperty("http.agent");
        }
        StringBuilder sb = new StringBuilder();
        for (int i = 0, length = userAgent.length(); i < length; i++) {
            char c = userAgent.charAt(i);
            if (c <= '\u001f' || c >= '\u007f') {
                sb.append(String.format("\\u%04x", (int) c));
            } else {
                sb.append(c);
            }
        }
        return sb.toString();
    }

    /**
     * 获取随机16位字符串
     *
     * @return 16位字符串
     */
    public static String getRandomNonce() {
        UUID uuid = UUID.randomUUID();
        String nonce = uuid.toString().replace("-", "");
        return MD5Util.MD5(nonce).substring(0, 16);
    }
}
